import axios, { AxiosInstance } from 'axios';
import { GlobalResp } from '@/models';
import Vue from 'vue';
import { BToast } from 'bootstrap-vue';

import { ToastPlugin } from 'bootstrap-vue';
import router from '@/router';
Vue.use(ToastPlugin);

//创建axios实例，
const service: AxiosInstance = axios.create({
    // baseURL: 'http://192.168.1.101:8090',
    // baseURL: 'http://192.168.1.106:8090',
    baseURL: '/prod-api',
    // baseURL: 'http://192.168.43.119:8090',
    timeout: 10000,
});

//请求拦截器
service.interceptors.request.use(
    config => {
        config.data = JSON.stringify(config.data);
        config.headers = {
            'Content-Type': 'application/json',
        };
        return config;
    },
    error => {
        Promise.reject(error);
    }
);

//响应拦截器
service.interceptors.response.use(
    response => {
        const resp: GlobalResp = response.data;
        //全局异常处理
        if (resp.code !== 0) {
            //如果包含业务逻辑错误
            const msg = resp.msg || '';
            new BToast().$bvToast.toast(msg, {
                title: '警告',
                toaster: 'b-toaster-top-center',
                solid: true,
                appendToast: false,
                autoHideDelay: 3000,
            });

            //错误处理
            switch (resp.code) {
                case 31:
                    router.push('/');
                    break;
            }
        }

        //仅返回数据
        return resp.data;
    },
    error => {
        // 超时处理
        if (JSON.stringify(error).includes('timeout')) {
            console.log('服务器响应超时，请刷新当前页');
        }
        return Promise.resolve(error.response);
    }
);

export default service;
